/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.logical.allhit.http;

import com.logical.allhit.gui.CaptchaImg;
import com.logical.allhit.gui.MainView;
import com.logical.allhit.setting.Setting;
import com.logical.allhit.setting.SettingChangeEvent;
import com.logical.allhit.setting.SettingChangeEventListener;
import com.logical.allhit.util.MsgLogger;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.params.ClientPNames;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.CoreProtocolPNames;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HTTP;

/**
 *
 * @author Sanjeet Jha
 */
public class HTTPClientAdd implements SettingChangeEventListener {

    private static final HTTPClientAdd instance = new HTTPClientAdd();
    private DefaultHttpClient httpClient;
    private HttpEntity entity;
    private String imageCode;
    private boolean isFirst;

    public String getImageCode() {
        return imageCode;
    }

    public void setImageCode(String imageCode) {
        this.imageCode = imageCode;
    }

    public static HTTPClientAdd getInstance() {
        return instance;
    }

    private HTTPClientAdd() {
        super();
        httpClient = new DefaultHttpClient();
        HttpParams params = new BasicHttpParams();
        params.setParameter(CoreProtocolPNames.USER_AGENT, Setting.getInstance().getUserAgent());
        params.setParameter(ClientPNames.DEFAULT_HOST, "promos.allhitdeals.com");
        httpClient.setParams(params);
        Setting.getInstance().addSettingChandeEventListener(this);
        isFirst = true;
    }

    @Override
    public void settingChenged(SettingChangeEvent evt) {
        httpClient = new DefaultHttpClient();
        HttpParams params = new BasicHttpParams();
        params.setParameter(CoreProtocolPNames.USER_AGENT, Setting.getInstance().getUserAgent());
        params.setParameter(ClientPNames.DEFAULT_HOST, "promos.allhitdeals.com");
        httpClient.setParams(params);
    }

    public String GETAdd(String url) {
        try {
            HttpGet get = new HttpGet(url);
            HttpResponse response = httpClient.execute(get);

            String json = new String();

            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    response.getEntity().getContent()));

            String line = "";
            while ((line = reader.readLine()) != null) {
                json += line;
            }
            entity = response.getEntity();
            if (entity != null) {
                entity.consumeContent();
            }
            return json;
        } catch (Exception e) {
            Logger.getLogger(HTTPClient.class.getName()).log(Level.WARNING, e.getMessage(), e);
            return "";
        }
    }

    public boolean login(String userName, String password) {
        try {
            String msg = "Client trying login to ADD server and User Name: " + userName;
            MsgLogger.getInstance().showMsg(msg);
            String script = "";
//            HttpPost httpPost = new HttpPost("http://202.87.47.29/~allhitdl/promos.php");
//            HttpPost httpPost = new HttpPost("http://202.87.47.29/~allhitdl/deals/promos.php");
            HttpPost httpPost = new HttpPost("http://promos.allhitdeals.com/deals/promos.php");
            List<NameValuePair> nvps = new ArrayList<NameValuePair>();
            nvps.add(new BasicNameValuePair("emailId", userName));
            nvps.add(new BasicNameValuePair("passwords", password));
            httpPost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
            HttpResponse response = httpClient.execute(httpPost);

            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    response.getEntity().getContent()));

            String line = "";
            while ((line = reader.readLine()) != null) {
                script += line;
            }
            entity = response.getEntity();
            if (entity != null) {
                entity.consumeContent();
            }

            msg = "Login successfully!";
            MsgLogger.getInstance().showMsg(msg);
            if(script.equals("<script>document.location.href='inbox.php'</script>")){
                isFirst = true;
                return true;
            }else{
                isFirst = false; 
                return false;
            }
        } catch (Exception e) {
            Logger.getLogger(HTTPClient.class.getName()).log(Level.WARNING, e.getMessage(), e);
            return false;
        }
    }

    public void addClick(String url,String imageCode, String referer) {
        try {
            if (isFirst) {
                new CaptchaImg(MainView.getInstance().getFram(), true, imageCode, CaptchaImg.add_image_code).setVisible(true);
                isFirst = false;
            }
            HttpPost httpPost = new HttpPost(url);
            String script = "";
            List<NameValuePair> nvps = new ArrayList<NameValuePair>();
            nvps.add(new BasicNameValuePair("x", "25"));
            nvps.add(new BasicNameValuePair("y", "16"));
            nvps.add(new BasicNameValuePair("letters_code", this.imageCode));
            httpPost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
            httpPost.addHeader("Accept-Encoding", "gzip, deflate");
            httpPost.addHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
            httpPost.addHeader("Connection", "keep-alive");
            httpPost.addHeader("x-insight", "activate");
            httpPost.addHeader("Referer", referer);
            HttpResponse response = httpClient.execute(httpPost);

            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    response.getEntity().getContent()));

            String line = "";
            while ((line = reader.readLine()) != null) {
                script += line;
            }

            entity = response.getEntity();
            if (entity != null) {
                entity.consumeContent();
            }
            MsgLogger.getInstance().showMsg(script);
        } catch (Exception e) {
            Logger.getLogger(HTTPClient.class.getName()).log(Level.WARNING, e.getMessage(), e);
        }
    }
    
    
    public byte[] GETIMAGE(String url) {
        try {
            HttpGet get = new HttpGet(url);
            HttpResponse response = httpClient.execute(get);

            //byte[] json = new byte[Integer.parseInt(response.getHeaders("Content-Length")[0].getValue())];
            byte[] json = new byte[1024 * 1024 * 3];
            DataInputStream dataIs = new DataInputStream(response.getEntity().getContent());
            //dataIs.readFully(json);

            byte[] line = new byte[50];
            int i = 0;
            while (true) {
                try {
                    dataIs.readFully(line);
                    System.arraycopy(line, 0, json, i* 50, 50);
                    i++;
                } catch (Exception ex) {
                    break;
                }
            }
            
            byte[] output = new byte[i * 50];
            
            System.arraycopy(json, 0, output, 0, i * 50);
            
            entity = response.getEntity();
            if (entity != null) {
                entity.consumeContent();
            }
            return output;
            
        } catch (Exception e) {
            Logger.getLogger(HTTPClient.class.getName()).log(Level.WARNING, e.getMessage(), e);
            return null;
        }
    }
    
    
}
